package com.jianganming.serial;

import java.io.*;

public class JavaSerializerWithFile implements ISerializer {
    @Override
    public <T> byte[] serialize(T obj) {
        ObjectOutputStream out = null;
        FileOutputStream outputStream = null;
        try {
            File file = new File("user");
            outputStream = new FileOutputStream(file);
            out = new ObjectOutputStream(outputStream);
            out.writeObject(obj);

            FileInputStream in = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            for (int readNum; (readNum = in.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(out != null){
                    out.close();
                }
                if(outputStream != null){
                    outputStream.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return new byte[0];
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) {
        ByteArrayInputStream in = new ByteArrayInputStream(data);
        ObjectInputStream inputStream=null;
        try {
            inputStream = new ObjectInputStream(in);
            Object o = inputStream.readObject();
            return (T)o;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                in.close();
                if (inputStream != null) {
                    inputStream.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }
}
